/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2024 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "dma.h"
#include "i2c.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "bsp_led.h"
#include "bsp_key.h"
#include "stdio.h"
#include "bsp_pid.h"
#include "bsp_pid_assistant.h"
#include "outputdata.h"
#include "bsp_mpu6050.h"
#include "kalman.h"
#include "bsp_control.h"
#include "string.h"
//#include "b"

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */


/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */
  int result;


  //1.PID参数初始化
  PID_Struct_Init(&PID_Struct_Vertical, CURVES_CH1);
  PID_Struct_Init(&PID_Struct_Velocity, CURVES_CH2);
  PID_Struct_Init(&PID_Struct_Turn, CURVES_CH3);

  /* 以复位时的角度为平衡点 */
//  1.第一组数据（小电机）
//  SET_PID_Param(&PID_Struct_Vertical,500,0,0.8);
//  SET_PID_Param(&PID_Struct_Velocity,0.415,0,0);
//  2.第二组数据
//  SET_PID_Param(&PID_Struct_Vertical,411,0,0.811);
//  SET_PID_Param(&PID_Struct_Velocity,0.588,0,0);

//  2.第一组数据（带电池）大电机
//  SET_PID_Param(&PID_Struct_Vertical,1111,0,2.555);
//  SET_PID_Param(&PID_Struct_Velocity,-0.155,-0.000333,0);
//  2.第三组数据（带电池）
  //1.PID-PD直立环。
//  SET_PID_Param(&PID_Struct_Vertical,995,0,2.103);
  SET_PID_Param(&PID_Struct_Vertical,888,0,2.103);
  //2.PID-PI速度环。
  SET_PID_Param(&PID_Struct_Velocity,-0.1666,-0.0022,0);
  PID_Struct_Velocity.LPF = 0.7;
  //3.PID-PD转向环。
  SET_PID_Param(&PID_Struct_Turn,1.403,0,0);

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_I2C1_Init();
  MX_TIM4_Init();
  MX_TIM5_Init();
  MX_USART1_UART_Init();
  MX_USART3_UART_Init();
  MX_TIM8_Init();
  /* USER CODE BEGIN 2 */
  //2.设置电机无输出
  HAL_TIM_PWM_Start(&htim8,TIM_CHANNEL_3);
  HAL_TIM_PWM_Start(&htim8,TIM_CHANNEL_4);
  Motor_PWM_Out(0, 0);

  //3.开始捕获电机编码器脉冲
  HAL_TIM_Encoder_Start(&htim4,TIM_CHANNEL_ALL);
  HAL_TIM_Encoder_Start(&htim5,TIM_CHANNEL_ALL);

  //4.MPU6050初始化
  result = MPU6050_DMP_Init();
  if (result != 0) //鍒ゆ柇MPU6050鍒濆鍖栨槸鍚︽垚鍔?
  {
    while (result) {
      printf("MPU6050 DMP Init ERR! result = %d\r\n", result);
      HAL_Delay(1000);
      result = MPU6050_DMP_Init();
    }
  } else {
    printf("MPU6050 DMP Init successful. result = %d\r\n", result);
  }
  /* EXTI interrupt init*/
  //MPU6050初始化成功后再使能捕获MPU6050 IN引脚的中断
  HAL_NVIC_SetPriority(EXTI1_IRQn, 0, 0);
  HAL_NVIC_EnableIRQ(EXTI1_IRQn);
  //卡尔曼滤波初始化
  kalman_init(&kf, Roll, 1);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1) {
    if (__KEY1_SCAN == _KEY_DOWN) {
      _LED_BLUE_Toggle;
      printf("_LED_BLUE_Toggle");
    }
    if (__KEY2_SCAN == _KEY_DOWN) {
      _LED_BLUE_Toggle;
    }

    //信息打印
    HAL_Delay(100);
    SET_OutData(Roll,kf.x_hat,0,0);
    OutPut_Data();
//    HAL_GPIO_TogglePin(LED_GREEN_GPIO_Port,LED_GREEN_Pin);
//    sprintf(SendBuffer,"\r\nRoll:%5.3f\r\nGyro[0]:%d\r\nGyro[2]:%d\r\n",Roll,Gyro[0],Gyro[2]);
//    HAL_UART_Transmit(&huart3, SendBuffer, strlen(SendBuffer), HAL_MAX_DELAY);
  }

  /* USER CODE END WHILE */

  /* USER CODE BEGIN 3 */

  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                                |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1) {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
